/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.gateway.custom;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: visen
 * @Date: 2018/2/1
 * @Description: simple implement for concurrency
 */
public class FastRateLimiter {
    private long permitsPerSecond;
    private AtomicLong atomicLong;
    private long curPermit;
    private ReentrantReadWriteLock lock;
    private volatile long expireTime;
    private long duration;

    private void refresh() {
        this.expireTime = System.currentTimeMillis() + duration;

    }

    private FastRateLimiter(long permitsPerSecond, int amout, TimeUnit unit) {
        this.permitsPerSecond = permitsPerSecond;
        atomicLong = new AtomicLong(0);
        lock = new ReentrantReadWriteLock();
        this.duration = unit.toMillis(amout);
        refresh();
    }


    public static FastRateLimiter create(int permitsPerSecond, int amout, TimeUnit unit) {
        return new FastRateLimiter(permitsPerSecond, amout, unit);
    }

    public long remainingPermit() {
        return this.curPermit;
    }

    public boolean tryAcquire() {
        if (expireTime < System.currentTimeMillis()) {
            try {
                lock.writeLock().lock();
                refresh();
                atomicLong.set(1);
                return true;
            } catch (Exception e) {
            } finally {
                lock.writeLock().unlock();
            }
        }
        try {
            lock.readLock().lock();
            curPermit = atomicLong.addAndGet(1);
            if (curPermit > permitsPerSecond) {
                return false;
            }
        } catch (Exception e) {
        } finally {
            lock.readLock().unlock();
        }

        return true;
    }

    public static void main(String[] args) {
        FastRateLimiter rateLimiter = FastRateLimiter.create(2, 60, TimeUnit.SECONDS);
        rateLimiter.tryAcquire();
    }
}
